const express = require("express")
const router = express.Router()
const { v1: uuidV1 } = require("uuid")
var bodyParser = require("body-parser")

// 创建application/json 解析器
var jsonParser = bodyParser.json()

let connectDAO = require('../connect')
async function dbTrainInfo(sql,processData) {
  //processData为回调方法
  await connectDAO.queryDataBySQL(sql, processData);
}

// 留言
router.put("/put_commentFriendLink", function (req, res) {
    let {  userId,avatarUrl,nickname, comment ,BrowserVersion,System} = req.body;
    // 评论格式化
    comment = {content:comment,commentTime:(new Date()).getTime() ,commentId:uuidV1()}
    dbTrainInfo(`INSERT INTO leavingmessage VALUES ('${comment.commentId}','${userId}','${avatarUrl}','${nickname}','${comment.content}','${comment.commentTime}','[]','${BrowserVersion}','${System}','无');`).then(()=>{
        res.send({code:200,msg:'留言成功'})
    }).catch(()=>{
        res.send({code:201,msg:'失败'})
    })
})
// 获取留言
router.get("/get_commentFriendLink", function (req, res) {
    let data = {}
    dbTrainInfo(`SELECT * FROM leavingmessage ORDER BY commentTime DESC;`,(result)=>{
        data = result
    }).then(()=>{
        res.send({code:200,msg:'ok',data})
    }).catch((err)=>{
        console.log(err);
        res.send({code:201,msg:'fail'})
    })
})

// 回复留言
router.put('/put_replyCommentFriendLink',function(req,res){
    let { id,content ,BrowserVersion,System} = req.body;
    content = {content,commentTime:(new Date()).getTime(),BrowserVersion,System}
    dbTrainInfo(`SELECT reply FROM leavingmessage WHERE id = '${id}';`,(result)=>{
        result = JSON.parse(result[0].reply)
        result.push(content)
        dbTrainInfo(`UPDATE leavingmessage SET reply = '${JSON.stringify(result)}' WHERE id = '${id}';`).
        then(()=>{
            res.send({code:200,msg:'ok'})
        }).
        catch((err)=>{
            console.log(err);
            res.send({code:201,msg:'fail'})
        })
    })
})

// 获取友链
router.get('/get_friendLink',function(req,res){
    let data = []
    dbTrainInfo(`SELECT * FROM friendlink;`,(result)=>{
        data = result
    }).then(()=>{
        res.send({code:200,msg:'ok',data})
    }).
    catch((err)=>{
        console.log(err);
        res.send({code:201,msg:'fail'})
    })
})
router.get('/get_musicList',function(req,res){
    let data = []
    dbTrainInfo(`SELECT * FROM music;`,(result)=>{
        data = result
    }).then(()=>{
        res.send({code:200,msg:'ok',data})
    }).
    catch((err)=>{
        console.log(err);
        res.send({code:201,msg:'fail'})
    })
})



module.exports = router;